package com.marvin.spring.intercept.learning.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @ClassName: TimeInterceptor
 * @Description:
 * @Author Marvin
 * @Date 2019/5/22 22:28
 */
@Slf4j
@Component
public class TimeInterceptor  implements HandlerInterceptor {
    /**
     * @Author Administrator
     * @Description  方法调用前执行（前置处理器）
     * @Date 22:31 2019/5/22
     * @Param [request, response, handler]
     * @return boolean
     **/
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setAttribute("startTime", new Date().getTime());
        log.info("Interceptor： -->preHandle");
        log.info("Interceptor： -->Bean 类型：" + ((HandlerMethod)handler).getBean().getClass().getName());
        log.info("Interceptor： -->方法名：" + ((HandlerMethod)handler).getMethod().getName());
        // 返回决定是否调用后续方法
        return true;
    }

    /**
     * @Author Administrator
     * @Description 方法成功调用之后执行,抛出异常不会调用（后置处理器）
     * @Date 22:32 2019/5/22
     * @Param [request, response, handler, modelAndView]
     * @return void
     **/
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        Long startTime = (Long)request.getAttribute("startTime");
        log.info("Interceptor： -->postHandle");
        log.info("Interceptor： -->Interceptor time: " + (new Date().getTime() - startTime));
    }

    /**
     * @Author Administrator
     * @Description 方法调用之后执行，无论是否抛异常,正常在postHandle后
     * @Date 22:33 2019/5/22
     * @Param [request, response, handler, ex]
     * @return void
     **/
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("Interceptor： -->afterCompletion");
        Long startTime = (Long)request.getAttribute("startTime");
        log.info("Interceptor： -->Interceptor time: " + (new Date().getTime() - startTime));
        log.info("Interceptor： -->ex :" + ex);
    }
}
